import { defineEventHandler, getQuery } from 'h3'
import { getPool } from '../util/mysql'
import { recordLog } from '../util/log'

export default defineEventHandler(async (event: any) => {
  const q = getQuery(event) as any
  const id = q.id || q.product_id || q.productId
  if (!id) {
    event.node.res.statusCode = 400
    return { status: 400, message: 'missing id' }
  }

  try {
    const pool = await getPool()
    const [rows]: any = await pool.execute(`SELECT id,product_name,price,image_base64,detail FROM lin_product WHERE id = ? AND is_deleted = 0 LIMIT 1`, [id])
    if (!Array.isArray(rows) || rows.length === 0) return { status: 404, message: 'not found' }
    return { status: 200, data: rows[0] }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event, { message: `product.get error ${String(err?.message || err)}`, userId: 0 })
    return { status: 500, message: String(err?.message || err) }
  }
})
